"""
纯MySQL版本交易记录系统
Version: 1.0
"""
import logging
import uuid
from datetime import datetime
from typing import Optional

import pymysql
from pymysql import Connection
from pymysql.cursors import Cursor
from pymysql.err import OperationalError

# 日志配置
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename='trade_recorder.log'
)

class TradeRecorder:
    """
    交易记录器 - 纯MySQL版本
    """
    
    def __init__(self, host: str, port: int, user: str, 
                 password: str, db_name: str):
        """
        初始化数据库连接池
        """
        self.db_config = {
            'host': host,
            'port': port,
            'user': user,
            'password': password,
            'db': db_name,
            'charset': 'utf8mb4',
            'cursorclass': pymysql.cursors.DictCursor,
            'autocommit': False
        }
        
    def get_connection(self) -> Connection:
        """
        获取数据库连接
        """
        try:
            return pymysql.connect(**self.db_config)
        except OperationalError as e:
            logging.error(f"数据库连接失败: {e}")
            raise
    
    def record_order(self, symbol: str, direction: str, 
                    offset: str, price: float, 
                    volume: int) -> str:
        """
        记录交易订单
        """
        order_id = str(uuid.uuid4())
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
        conn = self.get_connection()
        try:
            with conn.cursor() as cursor:
                # 插入订单记录
                sql = """
                INSERT INTO trade_orders 
                (order_id, symbol, direction, offset_flag, 
                 price, volume, status, order_time)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
                """
                cursor.execute(sql, (
                    order_id, symbol, direction, offset, 
                    price, volume, 'PENDING', timestamp
                ))
                
                # 插入交易记录
                sql = """
                INSERT INTO trade_records 
                (order_id, symbol, direction, offset, 
                 volume, price, timestamp)
                VALUES (%s, %s, %s, %s, %s, %s, %s)
                """
                cursor.execute(sql, (
                    order_id, symbol, direction, offset, 
                    volume, price, timestamp
                ))
                
                conn.commit()
                return order_id
                
        except Exception as e:
            conn.rollback()
            logging.error(f"记录订单失败: {e}")
            raise
        finally:
            conn.close()
    
    def update_order_status(self, order_id: str, 
                           status: str, traded_volume: Optional[int] = None):
        """
        更新订单状态
        """
        timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
        conn = self.get_connection()
        try:
            with conn.cursor() as cursor:
                if traded_volume:
                    sql = """
                    UPDATE trade_orders 
                    SET status = %s, 
                        traded_volume = %s, 
                        update_time = %s
                    WHERE order_id = %s
                    """
                    cursor.execute(sql, (status, traded_volume, timestamp, order_id))
                else:
                    sql = """
                    UPDATE trade_orders 
                    SET status = %s, 
                        update_time = %s
                    WHERE order_id = %s
                    """
                    cursor.execute(sql, (status, timestamp, order_id))
                
                conn.commit()
                
        except Exception as e:
            conn.rollback()
            logging.error(f"更新订单状态失败: {e}")
            raise
        finally:
            conn.close()

# 使用示例
if __name__ == "__main__":
    # 从配置文件读取数据库配置
    recorder = TradeRecorder(
        host="172.28.196.123",
        port=3306,
        user="remote_admin",
        password="Admin@szlwy68",
        db_name="trade_monitor_v2"
    )
    
    # 记录新订单
    order_id = recorder.record_order(
        symbol="rb2405",
        direction="BUY",
        offset="OPEN",
        price=3500.0,
        volume=1
    )
    
    # 更新订单状态
    recorder.update_order_status(
        order_id=order_id,
        status="FILLED",
        traded_volume=1
    )